package com.ticket.server;

import com.ticket.service.TicketService;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * @Author: lihua
 * @Date: 2024/1/13 23:31
 * @Version: v1.0.0
 * @Description:
 **/
public class ServerThread implements Runnable{

    private TicketService ticketService = new TicketService();
    private Socket socket;
    public ServerThread(){}

    public ServerThread(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        System.out.println("接收到客户请求~");
        DataInputStream inputStream = null;
        DataOutputStream outputStream = null;
        try {
            inputStream = new DataInputStream(socket.getInputStream());
            outputStream = new DataOutputStream(socket.getOutputStream());
            boolean isExit = false;
            while (!isExit){
                String params = inputStream.readUTF();
                if(params != null && !params.isEmpty()){
                    String [] paramArray = params.split("&");
                    // 1、查询余票 ，2、查询自己的票，3,购票，4,退票
                    String result = "";
                    switch (paramArray[0]){
                        case "1":
                            result = ticketService.getAllTicketInfo();
                            break;
                        case "2":
                            result = ticketService.getUserOrder(paramArray[1]);
                            break;
                        case "3":
                            result = ticketService.buyTicket(Integer.valueOf(paramArray[1]),paramArray[2]);
                            break;
                        case "4":
                            result = ticketService.deleteOrder(paramArray[1]);
                            break;
                        case "5":
                            isExit = true;
                            break;
                        default:
                            result = "参数错误!";
                            break;
                    }
                    outputStream.writeUTF(result);
                    outputStream.flush();
                }
            }
            System.out.println("用户已退出！线程关闭！");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }

    }
}
